<template>
  <div class="app-container" v-loading="pageLoading">
    <el-button type="primary" class="fr" @click="createItems" v-permission="'material.add'">创建</el-button>
    <div class="filter-container">
      <!-- <el-input style="width: 260px;" placeholder="输入备件/编码按回车" clearable class="filter-item"
        @keyup.enter.native="research" @clear="research" v-model="query.type_id">
      </el-input> -->
      <el-cascader v-model="query.type_id" filterable style="width: 260px;" placeholder="设备类型" clearable
        class="filter-item" @keyup.enter.native="research" @clear="research" :props="MachineTypeProps"
        :options="MachineType">
      </el-cascader>
      <el-button class="filter-item" type="success" plain @click="research">查询</el-button>
      <el-button class="filter-item" type="info" plain @click="exportData" :loading="exportLoading">导出 </el-button>
    </div>
    <z-table :list="list" :tableProps="tableProps" :columns="columns" @editItem="editItem" @deleteItem="deleteItem">
      <template v-slot:content="v">
        <span v-if="v.key == 'seeFiles'">
          <span @click.stop="seeFiles(v.row)" class="icon-class text-blue">
            <svg-icon icon-class="documentation" />
          </span>
        </span>

        <span v-else-if="v.key == 'status'" class="text-label" :style="{background:statusColor[v.row[v.key]]}">
          {{getMatchingData(v.row[v.key],'status')}}
        </span>
        <span v-else>{{ v.row[v.key] }}</span>
      </template>
      <template v-slot:operation="v">
        <a href="javascript:;" class="text-yellow" @click="repair(v.row)">报修</a>
        <a href="javascript:;" class="text-blue" @click="editItem(v.row)">编辑</a>
        <a style="margin-left:5px;" href="javascript:;" class="text-red" @click="deleteItem(v.row)">删除</a>
      </template>
    </z-table>
    <z-pagination :pagination="pagination" :total="total" :page.sync="query.page" :limit.sync="query.size"
      @change="getList"></z-pagination>
    <z-form-dialog :name="name" :data="data" :formProps="formProps" :fields="fields" @submit="submit"
      :submitLoading="submitLoading" :visible.sync="editFormVisible">
      <template v-slot:footer>

        <el-button @click="editFormVisible = false">取消</el-button>
        <!-- <el-button type="warning" @click.native="submit" :loading="submitLoading">保存
        </el-button> -->
        <el-button type="primary" @click.native="submit" :loading="submitLoading">确认
        </el-button>
      </template>
    </z-form-dialog>
    <!-- 附件预留 -->
    <previewFiles :previewFilesShow="previewFilesShow" :fildData="fildData" />
  </div>
</template>

<script>
import commonMixin from '@/views/_common/mixin'
import previewFiles from '@/views/tpm/components/previewFiles'
import { deleteChildren } from '@/utils/index.js'
export default {
  name: 'reportForRepairManage',
  mixins: [commonMixin],
  components: { previewFiles },
  props: {},
  data() {
    return {
      query: {
        type_id: '',
        page: 1,
        size: 10,
      },
      name: '报修单',
      postForList: true,
      api: this.$api.TpmRepairRequest,
      baseUrl: this.$api.baseUrl,
      tableProps: {
        border: true,
        opsColWith: 140,
        fixed: false,
        hideOperations: false,
      },
      MachineType: [],
      MachineTypeProps: {
        label: 'machine_type_name',
        value: 'id',
        children: 'child',
        emitPath: false,
      },
      fildData: [],
      columns: [
        { title: '报修单号', key: 'code', width: 100, fixed: 'left' },
        { title: '设备类型', key: 'machine_type_name', width: 100, fixed: 'left' },
        { title: '设备编码', key: 'machine_name', width: 140 },
        { title: '故障类型', key: 'fault_type_name', width: 120 },
        { title: '故障描述', key: 'description', minWidth: 80 },
        { title: '查看附件', key: 'seeFiles', width: 100 },
        { title: '期望维修日期', key: 'expect_date', width: 140 },
        { title: '报修人', key: 'applicant', width: 120 },
        { title: '报修时间', key: 'request_date', width: 140 },
        { title: '维修岗位', key: 'post_name', width: 80 },
        { title: '状态', key: 'status', width: 100 },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '最后修改时间', key: 'modify_time', width: 140 },
      ],

      fields: [
        {
          title: '设备类型',
          key: 'type_id',
          span: 12,
          name: 'cascader',
          required: true,
          props: {
            filterable: true,
            checkStrictly: true,
            props: {
              children: 'child',
              value: 'id',
              label: 'machine_type_name',
              emitPath: false,
            },
          },
          events: {
            change: this.typeChange,
          },
          options: [],
        },
        {
          title: '设备编码',
          key: 'machine_id',
          span: 12,
          name: 'select',
          options: [],
        },
        {
          title: '故障类型',
          key: 'fault_type_id',
          span: 12,
          name: 'select',
          options: [],
          props: { filterable: true, remote: true, clearable: true, 'remote-method': this.getFaultType },
        },

        { title: '期望维修日期', key: 'expect_date', span: 12, name: 'date' },
        { title: '维修岗位', key: 'post_id', span: 12, name: 'select', options: [] },

        { title: '故障描述', key: 'description', span: 24, name: 'textarea' },
        {
          title: '上传附件',
          key: 'file_list',
          span: 24,
          name: 'fileUploader',
          tips: '不能大于20M',
          props: {
            action: '',
            // accept: '.jpg,.png,.pdf,',
            limit: 5,
            autoUpload: false,
            multiple: true,
            'on-change': this.uploadOnchange,
            'before-remove': this.beforeRemove,
            'on-preview': this.onPreview,
            'on-exceed': this.handleExceed,
          },
        },
      ],
      // 报修状态
      statusOptions: [
        { label: '待报修', value: 0 },
        { label: '已报修', value: 1 },
        {
          label: '已完成',
          value: 2,
        },
      ],
      statusColor: ['#e6a23c', '#409eff', '#67c23a'],
      postData: [],
      FaultTypeData: [],
      // 上传数据
      formData: new FormData(),
      deleteArray: [],
      // 预览组件
      previewFilesShow: false,
    }
  },
  computed: {},
  watch: {},
  created() {
    this.research()
    this.getMachineType()
    this.getPost()
    this.getFaultType()
  },
  mounted() {},
  methods: {
    getMachineType() {
      this.$request(this.baseUrl + 'Tpm/MachineType/GetTreeList').then((r) => {
        let tmp = deleteChildren(r, 'child')
        this.MachineType = tmp
        let tmpMa = this.fields.find((i) => i.key == 'type_id')
        tmpMa.options = tmp
      })
    },
    // 获取岗位
    getPost() {
      let Data = {
        page: 1,
        size: 100,
      }
      this.$request(this.baseUrl + 'Tpm/TpmEquipmentPost/GetList', Data, 'post').then((r) => {
        const { list } = r
        this.postData = list.map((i) => ({
          label: i.positions_name,
          value: i.id,
        }))
        this.getFieldConfig('post_id').options = this.postData
      })
    },
    // 提交文件
    submit() {
      let Data = {
        baseData: this.data,
        deleteArray: this.deleteArray,
      }
      // this.data.deleteArray = this.deleteArray
      this.formData.append('model', JSON.stringify(Data))
      this.submitLoading = true
      this.$request(this.baseUrl + 'Tpm/TpmRepairRequest/add', this.formData, 'post')
        .then((r) => {
          this.$message.success('操作成功')
          this.editFormVisible = false
          this.deleteArray = []
          this.getList()
        })
        .finally(() => {
          this.submitLoading = false
        })
        .finally(() => {
          this.formData = new FormData()
        })
    },
    typeChange(v) {
      let data = {
        machine_type_id: v,
        page: 1,
        size: 100,
      }
      this.$request(this.baseUrl + 'Tpm/Machine/GetList', data, 'post').then((r) => {
        const { list } = r
        let options = list.map((i) => ({
          label: i.machine_name,
          value: i.id,
        }))
        this.getFieldConfig('machine_id').options = options
      })
    },
    // 创建数据
    createItems() {
      this.formData = new FormData()

      this.createItem()
    },
    getMatchingData(val, code) {
      if (code == 'status') {
        let tmp = this.statusOptions.find((i) => i.value == val)
        return tmp ? tmp.label : ''
      }
    },
    // 报修
    repair(v) {
      this.$confirm('是否确定报修此维修单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$request(this.api + 'RepairRequestToRepairOrder/' + v.id, {}, 'post').then(() => {
            this.$message.success('报修成功')
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消认领',
          })
        })
        .finally(() => {})
    },
    // 编辑
    editItem(v) {
      this.pageLoading = true
      let url = this.api + 'getbyid'
      this.$request(url, {
        id: v.id,
      })
        .then((r) => {
          this.data = this.formatAfterGet(r)
          this.typeChange(v.type_id)
          this.editFormVisible = true
        })
        .finally(() => {
          this.pageLoading = false
        })
    },
    // 附件查看
    seeFiles(v) {
      this.$request(this.api + 'GetById', {
        id: v.id,
      }).then((r) => {
        const { file_list } = r
        this.fildData = file_list
        this.previewFilesShow = true
      })
    },
    // 故障类型远程搜索
    getFaultType(val) {
      let Data = {
        query: val ? val : '',
        page: 1,
        size: 100,
      }
      this.$request(this.baseUrl + 'Tpm/TpmFaultType/GetList', Data, 'post').then((r) => {
        const { list } = r
        this.FaultTypeData = list.map((i) => ({
          label: `${i.code} ${i.name}`,
          value: i.id,
        }))
        this.getFieldConfig('fault_type_id').options = this.FaultTypeData
      })
    },
    // 上传
    uploadOnchange(file, fileList) {
      let f = file.raw
      const isLt20M = f.size / 1024 / 1024 < 20
      if (!isLt20M) {
        fileList.splice(fileList.indexOf(f), 1)
        return this.$message.error('上传档案大小不能超过 20MB!')
      }
      this.formData.append('files', f)
    },
    // 清除附件
    beforeRemove(file, fileList) {
      return this.$confirm(`确定要删除${file.name}?`, 提示, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        if (file.FileId) {
          // 已经有附件了,进行删除
          this.deleteArray.push(file.FileId)
        } else {
          this.formData = new FormData()
          // 刚上传没有点确定
          fileList.forEach((i) => {
            if (!i.FileId && i.name != file.name) {
              this.formData.append('files', i.raw)
            }
          })
        }
      })
    },

    // 预览
    onPreview(file) {
      alert('没有接口看个毛')
    },
    // 超过最大上传数
    handleExceed() {
      return this.$message.warning('最多只能上传5张图片')
    },
  },
}
</script>

<style lang="less" scoped></style>